package com.thinkgem.jeesite.modules.sys.interceptor;

import com.thinkgem.jeesite.common.annotation.MobileApi;
import com.thinkgem.jeesite.common.annotation.MobileApiAnonymous;
import com.thinkgem.jeesite.common.exception.UserAuthorizationException;
import com.thinkgem.jeesite.common.utils.ControllerHelper;
import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.utils.TicketConfig;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.MobileUserContext;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by admin on 2017-12-5.
 */
public class MobileApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (ControllerHelper.findMethodOrClassLevelAnnotation(handler, MobileApi.class) == null) {
            return true;
        }
        if (ControllerHelper.findMethodOrClassLevelAnnotation(handler, MobileApiAnonymous.class) != null) {
            return true;
        }
        String ticket = request.getHeader("ticket");
        if (StringUtils.isBlank(ticket)) {
            throw new UserAuthorizationException("invalid ticket-001");
        }
        String key = TicketConfig.KEY_TKUSER + ticket;
        String userId = JedisUtils.get(key);
        if (StringUtils.isBlank(userId)) {
            throw new UserAuthorizationException("invalid ticket-002");
        }
        User currentUser = UserUtils.get(userId);
        if (currentUser == null) {
            throw new UserAuthorizationException("invalid ticket-003");
        }
        MobileUserContext.set(currentUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        MobileUserContext.clear();
    }
}
